﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using AddIn.EA.Architecture.ExternalResources;


namespace AddIn.EA.Architecture.ComponentLogic
{
    public interface IPackageBuilder
    {
        string Name { get; set; }
        IPackageBuilder Parent { get; }
        IPackageBuilder this[string name] { get; set; }
    }

    public class PackageBuilder : List<IPackageBuilder>, IPackageBuilder
    {
        private static Queue<string> _parameters;

        public PackageBuilder(IPackageBuilder parent)
        {
            this.Parent = parent;
        }

        public IPackageBuilder Parent { get; private set; }
        public string Name { get; set; }
        public IPackageBuilder this[string name]
        {
            get { return this[IndexOf(name)]; }
            set { this[IndexOf(name)] = value; }
        }

        public int IndexOf(string name)
        {
            foreach (IPackageBuilder package in this)
                if (package.Name == name)
                    return this.IndexOf(package);

            return -1;
        }

        public bool Contains(string name)
        {
            return (this.IndexOf(name) >= 0);
        }

        public static PackageBuilder LoadProcessStructure(params string[] parameters)
        {
            XmlDocument xml = ExternalResources.ProcessStructure.GetProcessStructureXml();
            return PackageBuilder.LoadPackages(xml, parameters);
        }

        private static PackageBuilder LoadPackages(XmlDocument xml, params string[] parameters)
        {
            _parameters = new Queue<string>(parameters);

            PackageBuilder package = PackageBuilder.LoadPackageItem(xml.DocumentElement, null);

            _parameters.Clear();

            return package;
        }

        private static PackageBuilder LoadPackageItem(XmlElement package, PackageBuilder parent)
        {
            bool isFixed = Convert.ToBoolean(package["Fixed"].InnerText);

            PackageBuilder builder = new PackageBuilder(parent);
            builder.Name = isFixed ? package["Name"].InnerText : _parameters.Dequeue();
            builder.LoadChildren(package["Children"]);

            return builder;
        }

        private void LoadChildren(XmlElement children)
        {
            foreach (XmlElement package in children.ChildNodes)
                this.Add(PackageBuilder.LoadPackageItem(package, this));
        }
    }
}
